<template>
  <div class="ai-assistant-container">
    <div class="chat-container">
      <!-- 聊天历史区域 -->
      <div class="chat-history" ref="chatHistoryRef">
        <div v-if="chatMessages.length === 0" class="welcome-message">
          <div class="welcome-content">
            <img src="../assets/images/logo.png" alt="Logo" class="welcome-logo" />
            <h2>欢迎使用懂车之家AI助手</h2>
            <p>您可以向我询问关于汽车的任何问题</p>
            <div class="suggestion-chips">
              <div 
                v-for="(suggestion, index) in suggestions" 
                :key="index" 
                class="suggestion-chip"
                @click="sendMessage(suggestion)"
              >
                {{ suggestion }}
              </div>
            </div>
          </div>
        </div>
        
        <div v-for="(message, index) in chatMessages" :key="index" class="message-container">
          <div :class="['message', message.isUser ? 'user-message' : 'ai-message']">
            <div class="message-avatar">
              <el-avatar v-if="message.isUser" :size="40" :src="userAvatar">{{ userInitials }}</el-avatar>
              <el-avatar v-else :size="40" :src="aiAvatar" class="ai-avatar"></el-avatar>
            </div>
            <div class="message-content">
              <div class="message-sender">{{ message.isUser ? '我' : 'AI助手' }}</div>
              <div class="message-text">{{ message.text }}</div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </div>
        </div>
        
        <!-- 加载中指示器 -->
        <div v-if="isLoading" class="loading-indicator">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="chat-input-container">
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="2"
          placeholder="输入您的问题..."
          resize="none"
          @keydown.enter.prevent="handleEnterPress"
          class="chat-input"
        />
        <el-button 
          type="primary" 
          :icon="ChatDotRound" 
          circle 
          class="send-button"
          :disabled="!userInput.trim() || isLoading"
          @click="sendMessage()"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue'
import { useUserStore } from '../store/user'
import { ChatDotRound } from '@element-plus/icons-vue'
import { aiService } from '../services/aiService'
import { ElMessage } from 'element-plus'

// 引入AI助手头像图片
import aiAvatar from '../assets/images/Ai-Agent.jpg'

// 状态
const userStore = useUserStore()
const chatHistoryRef = ref(null)
const userInput = ref('')
const chatMessages = ref([])
const isLoading = ref(false)
const conversationHistory = ref([]) // 用于存储与API通信的对话历史
const currentAiMessageIndex = ref(-1) // 当前AI消息在chatMessages中的索引

// 建议问题
const suggestions = [
  '什么车型适合家用？',
  '电动汽车和燃油车哪个更好？',
  '如何选择二手车？',
  '汽车保养周期是多久？'
]

// 计算属性
const userAvatar = computed(() => userStore.user?.avatar || '')
const userInitials = computed(() => {
  const name = userStore.user?.nickname || userStore.user?.username || '用户'
  return name ? name.charAt(0).toUpperCase() : 'U'
})

// 格式化当前时间
const formatTime = () => {
  const now = new Date()
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 发送消息
const sendMessage = async (text = null) => {
  const messageText = text || userInput.value.trim()
  if (!messageText || isLoading.value) return
  
  // 添加用户消息
  chatMessages.value.push({
    text: messageText,
    isUser: true,
    time: formatTime()
  })
  
  // 更新对话历史
  conversationHistory.value.push({
    role: "user",
    content: messageText
  })
  
  // 清空输入框
  userInput.value = ''
  
  // 滚动到底部
  await nextTick()
  scrollToBottom()
  
  // 显示加载状态
  isLoading.value = true
  
  try {
    // 先添加一个空的AI消息占位符
    const aiMessageIndex = chatMessages.value.length
    chatMessages.value.push({
      text: '',
      isUser: false,
      time: formatTime()
    })
    currentAiMessageIndex.value = aiMessageIndex
    
    // 调用AI服务（启用流式响应）
    await aiService.sendStreamMessage(messageText, conversationHistory.value, (chunk) => {
      // 逐字更新AI消息
      if (currentAiMessageIndex.value >= 0) {
        chatMessages.value[currentAiMessageIndex.value].text += chunk
        // 滚动到底部
        nextTick(() => {
          scrollToBottom()
        })
      }
    })
    
    // 更新对话历史
    if (currentAiMessageIndex.value >= 0) {
      conversationHistory.value.push({
        role: "assistant",
        content: chatMessages.value[currentAiMessageIndex.value].text
      })
    }
  } catch (error) {
    console.error('AI助手请求失败:', error)
    
    // 添加错误消息
    if (currentAiMessageIndex.value >= 0) {
      chatMessages.value[currentAiMessageIndex.value].text = '抱歉，我暂时无法回应，请稍后再试'
    } else {
      chatMessages.value.push({
        text: '抱歉，我暂时无法回应，请稍后再试',
        isUser: false,
        time: formatTime()
      })
    }
    
    ElMessage.error('网络请求失败，请检查网络连接')
  } finally {
    // 隐藏加载状态
    isLoading.value = false
    currentAiMessageIndex.value = -1
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 处理回车键
const handleEnterPress = (e) => {
  if (!e.shiftKey) {
    sendMessage()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatHistoryRef.value) {
    chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight
  }
}

// 检查AI服务健康状态
const checkAIServiceHealth = async () => {
  try {
    const response = await aiService.checkHealth()
    if (!response.success) {
      ElMessage.warning('AI助手服务异常，可能无法正常使用')
      console.warn('AI服务健康检查失败:', response.error)
    }
  } catch (error) {
    console.error('AI服务健康检查请求失败:', error)
    ElMessage.warning('无法连接到AI助手服务，请稍后再试')
  }
}

// 生命周期钩子
onMounted(() => {
  // 初始化时滚动到底部
  scrollToBottom()
  
  // 检查AI服务健康状态
  checkAIServiceHealth()
})
</script>

<style scoped>
.ai-assistant-container {
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.chat-container {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  height: calc(100vh - 140px);
  overflow: hidden;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
}

.chat-history::-webkit-scrollbar {
  width: 6px;
}

.chat-history::-webkit-scrollbar-thumb {
  background-color: rgba(144, 147, 153, 0.3);
  border-radius: 3px;
}

.welcome-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;
}

.welcome-content {
  text-align: center;
  max-width: 500px;
}

.welcome-logo {
  width: 80px;
  height: 80px;
  margin-bottom: 20px;
}

.welcome-content h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.welcome-content p {
  font-size: 16px;
  color: #606266;
  margin-bottom: 30px;
}

.suggestion-chips {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.suggestion-chip {
  background-color: #f0f2f5;
  color: #409EFF;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.suggestion-chip:hover {
  background-color: #e6f1fc;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-container {
  margin-bottom: 20px;
}

.message {
  display: flex;
  max-width: 80%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.ai-message {
  margin-right: auto;
}

.message-avatar {
  margin: 0 10px;
}

.ai-avatar {
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
  color: white;
  font-weight: bold;
}

.message-content {
  background-color: #f0f2f5;
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
}

.user-message .message-content {
  background-color: #e6f1fc;
  text-align: right;
  border-top-right-radius: 0;
}

.ai-message .message-content {
  background-color: #f0f2f5;
  border-top-left-radius: 0;
}

.message-sender {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-text {
  font-size: 15px;
  color: #303133;
  line-height: 1.5;
  word-break: break-word;
}

.message-time {
  font-size: 11px;
  color: #c0c4cc;
  margin-top: 4px;
  text-align: right;
}

.loading-indicator {
  display: flex;
  justify-content: flex-start;
  margin: 10px 0;
  padding-left: 50px;
}

.typing-indicator {
  display: flex;
  align-items: center;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  background-color: #409EFF;
  border-radius: 50%;
  display: inline-block;
  margin: 0 2px;
  opacity: 0.6;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.6);
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input-container {
  display: flex;
  align-items: center;
  padding: 15px;
  border-top: 1px solid #ebeef5;
  background-color: #fff;
}

.chat-input {
  flex: 1;
}

:deep(.el-textarea__inner) {
  border-radius: 20px;
  padding: 10px 15px;
  resize: none;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #dcdfe6;
}

:deep(.el-textarea__inner:focus) {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-color: #409EFF;
}

.send-button {
  margin-left: 10px;
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
  border: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s;
}

.send-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.send-button:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-assistant-container {
    padding: 10px;
  }
  
  .chat-container {
    height: calc(100vh - 120px);
  }
  
  .message {
    max-width: 90%;
  }
  
  .chat-history {
    padding: 15px;
  }
  
  .chat-input-container {
    padding: 10px;
  }
}
</style>